//
//  GBNoticeSetViewController.m
//  警用舆情平台
//
//  Created by 郭斌 on 15/5/15.
//  Copyright (c) 2015年 魏强. All rights reserved.
//

#import "GBNoticeSetViewController.h"
#import "AudioToolbox/AudioToolbox.h"
#import "AFNetworking.h"
#import "AFHTTPRequestOperation.h"
#import "GBNoticeTimeView.h"

//#define baseUrl @"http://ql.yunyq.cn/MobileAction.do?method=findNotice&token="
//#define opVoiceUrl @"http://ql.yunyq.cn/MobileAction.do?method=updateNoticeSound&token="
//#define opShockUrl @"http://ql.yunyq.cn/MobileAction.do?method=updateNoticeShock&token="
//#define baseUrl2 @"http://ql.yunyq.cn/MobileAction.do?method=updateNoticeTimeSpace&token="
//#define openBaseNoticeUrl @"http://ql.yunyq.cn/MobileAction.do?method=updateIsOpenNotice&token="

@interface GBNoticeSetViewController () <SelectResults>
{
    UIView *topView;
    UILabel *topLabel;
    UILabel *label1; //自定义
    UISwitch *switchOpenNotice;
    UISwitch *sound;
    UISwitch *zhengdong;
    BOOL openNotice;
    NSString *data1; //第一个日期
    NSString *data2; //第二个日期
    NSInteger whichBtn; //判断点击的是哪个时间按钮
    NSString *OpenNoticeUrl; //开启关闭的url
    NSString *AllUrl; //全部开关打开的url
    NSString *DoItYouselfUrl; //自定义的url
    
    //NSString *isOpenZhenDong; //是否开启过振动
    //NSString *isOpenSound; //是否开启声音
    //6.20改
    int isOpenVoice; //是否开启声音
    int isOpenZhengDong; //是否开启震动
    int isOpenNotice; //是否开启通知
    
    //9.8
    UILabel *openNoticeLabel; //显示是否开启关闭通知的label
    UILabel *timeLabel; //通知时段的选择结果 1 - 全天 2 - 自定义
    UILabel *openSoundLabel; //开启铃声label
    UILabel *openShockLabel; //开启震动label
    GBNoticeTimeView *backGroundView; //背景淡黑透明的view
    
}
@end

@implementation GBNoticeSetViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"通知设置";
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleDefault;
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.view.backgroundColor = WQColor(248, 249, 250);
    //初始化消息设置界面
//    NSTimer *timer=[NSTimer scheduledTimerWithTimeInterval:1.0f
//                                                    target:self
//                                                  selector:@selector(createMessage)
//                                                  userInfo:nil
//                                                   repeats:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self createMessage];
    });
    // Do any additional setup after loading the view.
}

#pragma mark - 代理返回选择的时间结果
-(void)selectTheResult:(NSArray *)result
{
    //选择全部
    if([result[0] isEqualToString:@"100"])
    {
        timeLabel.text = @"全天";
    }
    //自定义选择时间
    else
    {
        NSString *timez = [NSString stringWithFormat:@"%@:00 - %@:00", result[0], result[1]];
        timeLabel.text = timez;
    }
}

#pragma mark - 先请求数据
-(void)requestTheAllData
{
    KDAccount *account = [KDAccountTool account];
    //请求数据
    NSString *requestUrl = [NSString stringWithFormat:@"%@&method=findNotice&token=%@", ServerActionAddr ,account.tokens];
    NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestUrl]];
    //NSLog(@"%@",requestUrl);
    AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
    [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
        NSHTTPURLResponse *response = [op response];
        NSInteger code = [response statusCode];
        if (code == 200)
        {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
            if([jsonDict[@"status"] isEqualToString:@"ok"])
            {
                //NSLog(@"1");
                id beginT = jsonDict[@"data"][@"begTimeHour"];
                data1 = [NSString stringWithFormat:@"%d",[beginT intValue]];
                
                id endT = jsonDict[@"data"][@"endTimeHour"];
                data2 = [NSString stringWithFormat:@"%d",[endT intValue]];
                
                id isOV = jsonDict[@"data"][@"openSound"];
                isOpenVoice = [isOV intValue];
                
                id isOZ = jsonDict[@"data"][@"openShock"];
                isOpenZhengDong = [isOZ intValue];
                
                id isON = jsonDict[@"data"][@"isOpen"];
                isOpenNotice = [isON intValue];
            }
            else
            {
                UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"请求失败，请检查网络" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                [NSTimer scheduledTimerWithTimeInterval:1.50f
                                                 target:self
                                               selector:@selector(timerFireMethod:)
                                               userInfo:promptAlert
                                                repeats:YES];
                [promptAlert show];
            }
        }
    } failure:^(AFHTTPRequestOperation *op, NSError *error) {
        if (error) {
            //NSLog(@"req error %@",error);
        }
    }];
    [reqOper start];
}

#pragma mark - 初始化消息界面
-(void)createMessage
{
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 2, screenW, 195)];
    view1.backgroundColor = [UIColor whiteColor];
    view1.layer.borderWidth = 1.25;
    view1.layer.borderColor = [WQColor(228, 229, 230) CGColor];
    UIImageView *imageview1 = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 25, 25)];
    imageview1.image = [UIImage imageNamed:@"通知2"];
    openNoticeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 3, 100, 40)];
    openNoticeLabel.text = @"开启通知";
    openNoticeLabel.textColor = WQColor(121, 122, 122);
    openNoticeLabel.font = [UIFont systemFontOfSize:15];
    switchOpenNotice = [[UISwitch alloc] initWithFrame:CGRectMake(screenW - 70, 7, 40, 40)];
    
    //判断是否应该开启通知
    if(isOpenNotice == 0)
    {
        [switchOpenNotice setOn:YES animated:YES];
        openNoticeLabel.text = @"关闭通知";
    }
    else
    {
        [switchOpenNotice setOn:NO animated:YES];
        openNoticeLabel.text = @"开启通知";
    }
    [switchOpenNotice addTarget:self action:@selector(changeTheNoticeAction) forControlEvents:UIControlEventTouchUpInside];
    
    [view1 addSubview:imageview1];
    [view1 addSubview:openNoticeLabel];
    [view1 addSubview:switchOpenNotice];
    
    UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 45, screenW, 1)];
    line1.backgroundColor = WQColor(248, 249, 250);
    [view1 addSubview:line1];
    
    UIImageView *imageview2 = [[UIImageView alloc] initWithFrame:CGRectMake(15, 55, 25, 25)];
    imageview2.image = [UIImage imageNamed:@"时段"];
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 100, 35)];
    label2.text = @"通知时段";
    label2.textColor = WQColor(121, 122, 122);
    label2.font = [UIFont systemFontOfSize:15];
    timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(screenW - 130, 50, 100, 35)];
    if([data2 isEqualToString:@"24"])
    {
        timeLabel.text = @"全天";
    }
    else
    {
        timeLabel.text = [NSString stringWithFormat:@"%@:00 - %@:00", data1, data2];
    }
    timeLabel.textColor = WQColor(121, 122, 122);
    timeLabel.textAlignment = NSTextAlignmentCenter;
    timeLabel.font = [UIFont systemFontOfSize:15];
    
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, screenW, 1)];
    line2.backgroundColor = WQColor(248, 249, 250);
    [view1 addSubview:line2];
    
    UIButton *timeBtn = [UIButton buttonWithType:0];
    timeBtn.backgroundColor = [UIColor clearColor];
    timeBtn.frame = CGRectMake(0, 50, screenW, 40);
    [timeBtn addTarget:self action:@selector(selectTheTime) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:timeBtn];
    [view1 addSubview:imageview2];
    [view1 addSubview:label2];
    [view1 addSubview:timeLabel];

    UIImageView *imageview3 = [[UIImageView alloc] initWithFrame:CGRectMake(15, 100, 25, 25)];
    imageview3.image = [UIImage imageNamed:@"声音"];
    
    UIImageView *imageview7 = [[UIImageView alloc] initWithFrame:CGRectMake(15, 150, 25, 25)];
    imageview7.image = [UIImage imageNamed:@"震动"];
    
    UILabel *line3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 140, screenW, 1)];
    line3.backgroundColor = WQColor(248, 249, 250);
    [view1 addSubview:line3];
    
    openSoundLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 95, 100, 35)];
    openSoundLabel.text = @"开启声音";
    openSoundLabel.textColor = WQColor(121, 122, 122);
    openSoundLabel.font = [UIFont systemFontOfSize:15];
    openShockLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 145, 100, 35)];
    openShockLabel.text = @"开启震动";
    openShockLabel.textColor = WQColor(121, 122, 122);
    openShockLabel.font = [UIFont systemFontOfSize:15];
    
    sound = [[UISwitch alloc] initWithFrame:CGRectMake(screenW - 70, 100, 60, 28)];
    //NSLog(@"%d",isOpenVoice);
    if(isOpenVoice == 0)
    {
        [sound setOn:YES animated:YES];
        openSoundLabel.text = @"关闭声音";
    }
    else
    {
        [sound setOn:NO animated:YES];
        openSoundLabel.text = @"开启声音";
    }
    [sound addTarget:self action:@selector(sound:) forControlEvents:UIControlEventTouchUpInside];
    zhengdong = [[UISwitch alloc] initWithFrame:CGRectMake(screenW - 70, 150, 60, 28)];

    if(isOpenZhengDong == 0)
    {
        [zhengdong setOn:YES animated:YES];
        openShockLabel.text = @"关闭振动";
    }
    else
    {
        [zhengdong setOn:NO animated:YES];
        openShockLabel.text = @"开启振动";
    }
    [zhengdong addTarget:self action:@selector(zhengdong:) forControlEvents:UIControlEventTouchUpInside];
    
    [view1 addSubview:imageview3];
    [view1 addSubview:imageview7];
    [view1 addSubview:openShockLabel];
    [view1 addSubview:openSoundLabel];
    [view1 addSubview:sound];
    [view1 addSubview:zhengdong];
    
    [self.view addSubview:view1];
}

#pragma mark - 点击通知时段，生成选择时间界面
-(void)selectTheTime
{
    [UIView animateWithDuration:0.5 animations:^{
        backGroundView = [[GBNoticeTimeView alloc] initWithFrame:CGRectMake(0, 0, screenW, screenH)];
        backGroundView.delegate = self;
        [self.navigationController.view addSubview:backGroundView];
    }];
}

#pragma mark - 开启声音
-(void)sound:(UISwitch *)swt
{
    KDAccount *account = [KDAccountTool account];
    NSString *urll = nil;
    if(swt.isOn)
    {
        //NSLog(@"开启声音");
        urll = [NSString stringWithFormat:@"%@&method=updateNoticeSound&token=%@%@", ServerActionAddr,account.tokens,@"&isOpen=0"];
        //NSUserDefaults
        NSUserDefaults *userDefaults11 = [NSUserDefaults standardUserDefaults];
        //保存数据
        [userDefaults11 setObject:@"1" forKey:@"isOpenSound"];
        //同步数据
        [userDefaults11 synchronize];
    }
    else
    {
        urll = [NSString stringWithFormat:@"%@&method=updateNoticeSound&token=%@%@",ServerActionAddr,account.tokens,@"&isOpen=1"];
        //NSLog(@"关闭声音");
        //NSUserDefaults
        NSUserDefaults *userDefaults11 = [NSUserDefaults standardUserDefaults];
        //保存数据
        [userDefaults11 setObject:@"0" forKey:@"isOpenSound"];
        //同步数据
        [userDefaults11 synchronize];
    }
    NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urll]];
    //NSLog(@"%@",urll);
    AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
    [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
        NSHTTPURLResponse *response = [op response];
        NSInteger code = [response statusCode];
        if (code == 200)
        {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
            if([jsonDict[@"status"] isEqualToString:@"ok"])
            {
                UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                [NSTimer scheduledTimerWithTimeInterval:1.50f
                                                 target:self
                                               selector:@selector(timerFireMethod:)
                                               userInfo:promptAlert
                                                repeats:YES];
                [promptAlert show];
                if(!sound.isOn)
                {
                    [sound setOn:NO animated:YES];
                }
                else
                {
                    [sound setOn:YES animated:YES];
                }
            }
            else
            {
                UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置失败" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                [NSTimer scheduledTimerWithTimeInterval:1.50f
                                                 target:self
                                               selector:@selector(timerFireMethod:)
                                               userInfo:promptAlert
                                                repeats:YES];
                [promptAlert show];
            }
        }
    } failure:^(AFHTTPRequestOperation *op, NSError *error) {
        if (error) {
            //NSLog(@"req error %@",error);
            UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置失败" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [NSTimer scheduledTimerWithTimeInterval:1.50f
                                             target:self
                                           selector:@selector(timerFireMethod:)
                                           userInfo:promptAlert
                                            repeats:YES];
            [promptAlert show];
        }
    }];
    [reqOper start];
}

#pragma mark - 开启震动
-(void)zhengdong:(UISwitch *)swt
{
    KDAccount *account = [KDAccountTool account];
    //请求数据
    NSString *urll = nil;
    if(swt.isOn)
    {
        //NSLog(@"开启振动");
        urll = [NSString stringWithFormat:@"%@&method=updateNoticeShock&token=%@%@",ServerActionAddr,account.tokens,@"&isOpen=0"];
    }
    else
    {
        urll = [NSString stringWithFormat:@"%@&method=updateNoticeShock&token=%@%@",ServerActionAddr,account.tokens,@"&isOpen=1"];
        //NSLog(@"关闭振动");
    }
    NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urll]];
    //NSLog(@"%@",urll);
    AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
    [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
        NSHTTPURLResponse *response = [op response];
        NSInteger code = [response statusCode];
        if (code == 200)
        {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
            if([jsonDict[@"status"] isEqualToString:@"ok"])
            {
                //NSLog(@"1");
            }
        }
    } failure:^(AFHTTPRequestOperation *op, NSError *error) {
        if (error) {
            //NSLog(@"req error %@",error);
        }
    }];
    [reqOper start];
}

#pragma mark - 开启通知开关被打开
-(void)changeTheNoticeAction
{
    KDAccount *account = [KDAccountTool account];
    NSString *str1 = [account.token stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *string2 = [str1 stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]; //去掉+
    if(!switchOpenNotice.isOn)
    {
        //开启通知
        OpenNoticeUrl = [NSString stringWithFormat:@"%@&method=updateIsOpenNotice&token=%@%@%@",ServerActionAddr,string2,@"&isOpen=",@"1"];
    }
    else
    {
        //关闭通知
        OpenNoticeUrl = [NSString stringWithFormat:@"%@&method=updateIsOpenNotice&token=%@%@%@",ServerActionAddr,string2,@"&isOpen=",@"0"];
    }
//    NSLog(@"%@",OpenNoticeUrl);
    [self requestData1];
}

#pragma mark - 开启通知请求数据
-(void)requestData1
{
    NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:OpenNoticeUrl]];
    //NSLog(@"%@",urll);
    AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
    [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
        NSHTTPURLResponse *response = [op response];
        NSInteger code = [response statusCode];
        if (code == 200)
        {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
            if([jsonDict[@"status"] isEqualToString:@"ok"])
            {
                UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置成功" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                [NSTimer scheduledTimerWithTimeInterval:1.50f
                                                 target:self
                                               selector:@selector(timerFireMethod:)
                                               userInfo:promptAlert
                                                repeats:YES];
                [promptAlert show];
                if(!switchOpenNotice.isOn)
                {
                    [switchOpenNotice setOn:NO animated:YES];
                }
                else
                {
                    [switchOpenNotice setOn:YES animated:YES];
                }
            }
            else
            {
                UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置失败" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
                [NSTimer scheduledTimerWithTimeInterval:1.50f
                                                 target:self
                                               selector:@selector(timerFireMethod:)
                                               userInfo:promptAlert
                                                repeats:YES];
                [promptAlert show];
            }
        }
    } failure:^(AFHTTPRequestOperation *op, NSError *error) {
        if (error) {
            //NSLog(@"req error %@",error);
            UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"设置失败" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [NSTimer scheduledTimerWithTimeInterval:1.50f
                                             target:self
                                           selector:@selector(timerFireMethod:)
                                           userInfo:promptAlert
                                            repeats:YES];
            [promptAlert show];
        }
    }];
    [reqOper start];
}

#pragma mark - 弹出的对话框内容
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = nil;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //先请求数据
    [self requestTheAllData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end